package com.xframe.domain.role;


import com.xframe.domain.BaseModel;
import com.xframe.domain.emnus.EncryptionType;
import com.xframe.domain.emnus.XDelFlag;
import com.xframe.xdal.core.DataBaseAccess;
import com.xframe.xdal.core.annotation.*;
import com.xframe.xdal.core.constant.AutoFillType;
import com.xframe.xdal.core.constant.ErrorCode;
import com.xframe.xdal.core.constant.ErrorMsg;
import com.xframe.xdal.core.constant.OperateMark;
import com.xframe.xdal.core.domain.SysBaseEntity;
import com.xframe.xdal.core.exception.DalFrameException;
import com.xframe.xdal.core.model.AKQueryModel;
import com.xframe.xdal.core.model.ConditionValue;
import com.xframe.xdal.core.model.ConditionValueCollection;
import com.xframe.xdal.core.model.IModel;
import com.xframe.xdal.core.model.mapping.TableInfoBuilder;
import com.xframe.xdal.core.tran.XTransaction;
import com.xframe.xdal.core.util.EncryptUtil;
import com.xframe.xdal.core.util.StringUtil;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;


/**
 * @Description: 用户表
 * @ClassName: SysUser
 * @Author: xufeng
 * @CreateTime: 2023/4/3 16:59
 **/
@Log4j2
@Data
@Accessors(chain=true)
@XTable(value = "SYS_USER", label = "用户表")
@XSelectItem(keyName = "userId",codeName = "username",textName = "nickname")
@XBelongsTo(typeName = "com.xframe.domain.role.SysDept",foreignKey = "deptId", targetKey = "deptId",as = "refSysDept")
public class SysUser extends BaseModel implements IUserCredentials{
    /**
     * 用户ID
     */
    @AutoFill(AutoFillType.Snowflake)
    @XColumn(name = "user_id", primaryKeyFlag = true,desc = "用户ID")
    private Long userId;

    /**
     * 登录名
     */
    @XColumn(name = "username" , uniqueFlag = true,desc = "登录名",length = 64)
    private String username;

    /**
     * 登录密码
     */
    @XColumn(name = "password",desc = "登录密码",length = 500)
    @AutoFill(value = AutoFillType.MD5,overwrite= true,operateMark = OperateMark.Create | OperateMark.Update)
    private String password;

    /**
     * 用户名
     */
    @XColumn(name = "nickname",desc = "用户名",length = 50)
    private String nickname;

    /**
     * 随机盐
     */
    @XColumn(name = "salt",desc = "随机盐",length = 500,nullFlag = true)
    private String salt;


    /**
     * 电话
     */
    @XColumn(name = "phone",desc = "电话",length = 50,nullFlag = true)
    private String phone;

    /**
     * 头像
     */
    @XColumn(name = "avatar",desc = "头像",length = 500,nullFlag = true)
    private String avatar;

    /**
     * 部门ID
     */
    @XColumn(name = "dept_id",desc = "部门ID")
    private Long deptId;

    /**
     * 锁定标识 0-正常，9-锁定
     */
    @XColumn(name = "lock_flag",desc = "锁定标识",length = 10)
    @AutoFill(defVal = "0")
    private String lockFlag;

    /**
     * 工号
     */
    @XColumn(name = "job_no",desc = "工号",length = 50,nullFlag = true)
    private String jobNo;

    /**
     * 密级
     */
    @XColumn(name = "classification",desc = "密级",length = 100,nullFlag = true)
    private String classification;

    /**
     * 固定电话
     */
    @XColumn(name = "telephone",desc = "固定电话",length = 50,nullFlag = true)
    private String telephone;

    /**
     * 邮箱
     */
    @XColumn(name = "email",desc = "邮箱",length = 100,nullFlag = true)
    private String email;
    /**
     * 用户类别 1 = 总部 2 = 仓库  3 = 国内经销商  4 = 海外经销商
     */
    @XColumn(name = "org_type",desc = "用户类别",length = 10)
    private String orgType;

    /**
     * 组织机构编码
     */
    @XColumn(name = "org_code",desc = "组织机构编码",length = 50)
    private String orgCode;

    /**
     * 组织机构ID
     */
    @XColumn(name = "org_id",desc = "组织机构ID")
    private Long orgId;

    @Override
    public String getName() {
        return this.username;
    }


    @Override
    public String getLanguage() {
        return lang;
    }


    private String token;

    private String lang;

    /**
     * 部门
     */
    private SysDept refSysDept;




    /**
     * 授权菜单
     */
    @XTransaction
    @XAction(code = "authRole",desc = "授权角色",actionPage = "roleModal",actionType = "2")
    public Object authorizationRole(@XActionParameter(name = "ids") List<String> ids, IUserCredentials userCredentials){
        log.info("call SysUser.authorizationRole");
        try {
            log.info(ids);
            if(ids == null || ids.size() == 0){
                new DalFrameException(ErrorCode.ARGS_ERROR, ErrorMsg.ARGS_ERROR_MSG);
            }
            ConditionValueCollection conditionValueCollection = new ConditionValueCollection();
            conditionValueCollection.add(new ConditionValue("userId",this.userId));
            Integer delCount = DataBaseAccess.getInstance().deleteMany(TableInfoBuilder.BuildTableInfoByAnnotation(SysUserRole.class),conditionValueCollection);
            log.info(delCount);
            List<SysUserRole> userRoleList = new ArrayList<>();
            for(String id : ids){
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(Long.valueOf(id));
                userRole.setUserId(this.userId);
                userRole.setDelFlag(XDelFlag.getDefFlag());
                userRole.setBaseAttrVal(userCredentials);
                userRoleList.add(userRole);
            }
            DataBaseAccess.getInstance().batchCreate(SysUserRole.class,userRoleList);
            return "OK";
        } catch (DalFrameException exception) {
            throw exception;
        }
    }

    /**
     *  获取用户信息（登录使用）
     * @param username 账号
     * @return
     */
    public static SysUser getSysUser(String username){
        SysUser sysUser = DataBaseAccess.getInstance().findByAk(AKQueryModel.valueOf(SysUser.class, username, SysBaseEntity.FULL_DATA));
        return sysUser;
    }

    /**
     * 创建一个新的SysUser对象
     * @param IModel 实体对象
     * @return
     */
    public static SysUser createSysUser(IModel IModel){
        if(IModel instanceof IToUserInfo){
            IToUserInfo toUserInfo = (IToUserInfo)IModel;
            SysUser sysUser = new SysUser();
            sysUser.setUsername(toUserInfo.getUsername());
            sysUser.setNickname(toUserInfo.getNickname());
            sysUser.setOrgCode(toUserInfo.getOrgCode());
            sysUser.setOrgId(toUserInfo.getOrgId());
            sysUser.setOrgType(toUserInfo.getOrgType());
            sysUser.setDeptId(toUserInfo.getDeptId());

            return sysUser;
        }
        if(IModel instanceof SysUser){
            return (SysUser)(IModel);
        }
        return null;
    }


    public boolean checkPwd(String pwd,String type){
        try {
            String s = EncryptUtil.encryptMd5("123456");
            String enCr = pwd;
            if(!StringUtil.isEmpty(type)) {
                EncryptionType encryptionType = EncryptionType.fromString(type);
                switch (encryptionType){
                    case NONE:
                        //未加密不做处理
                        break;
                    case MD5:
                        enCr = EncryptUtil.encryptMd5(pwd);
                        break;
                    case AES:
                        enCr = EncryptUtil.encryptAES(pwd);
                        break;
                }
            }
            return this.getPassword().equals(enCr);
        } catch (Exception e) {
            return false;
        }
    }
}
